<template>
    <div class="comments-container">
        <h4>发表评论</h4>
        <hr>
        <textarea maxlength="140" placeholder="发表您的评论（不超过140字）" v-model="msg"></textarea>
        <mt-button type="primary" size="large" @click="postData">发表评论</mt-button>
        <div class="comments"  v-for="(item,i) in data" :key="item.add_time">
            <div class="comments-title">
                <span>第{{i+1}}楼</span>
                <span>用户：{{item.user_name}}</span>
                <span>发表时间：{{item.add_time | dateFormat}}</span>
            </div>
            <div class="comments-body">
                {{item.content == 'undefined' ? '该用户没有发表任何评论' : (item.content == '' ? '该用户没有发表任何评论' : item.content)}}
            </div>
        </div>
        <mt-button type="danger" plain size="large" @click="getMore">加载更多</mt-button>
    </div>
</template>


<script>
import { toast } from 'mint-ui';
export default {
    data() {
        return {
            data: [],
            page: 1,
            index: 0,
            msg: ''
        }
    },
    props: ['id'],
    methods: {
        getData() {
            this.$http.get(`api/getcomments/${this.id}?pageindex=${this.page}`).then(res => {
                if(res.body.status ==0 ) {
                    this.data = res.body.message;

                }
                else {
                    toast('获取数据失败');
                }
            }) 
        },
        getMore() {
            this.page++;
            this.$http.get(`api/getcomments/${this.id}?pageindex=${this.page}`).then(res => {
                if(res.body.status ==0 ) {
                    this.data = this.data.concat(res.body.message);
                }
                else {
                    toast('获取数据失败');
                }
            }) 
        },
        postData() {
            this.msg = this.msg.trim();
            if(this.msg.length == 0 ) {
                toast('请输入评论内容');
                return;
            }
            this.$http.post(`api/postcomment/${this.id}`,{ content: this.msg }).then( res => {
                if(res.body.status == 0) {
                    this.data.unshift({
                        user_name : '匿名用户',
                        add_time: Date.now(),
                        content: this.msg
                    });
                    this.msg = '';
                }else {
                    toast('评论提交失败');
                }
            })
        },
    },
    created() {
        this.getData();
    }
}
</script>


<style lang="less" scope>
    .comments-container {
        textarea {
            min-height: 100px;
            border-radius: 5px;
            margin: 0;
        }
        button {
            margin: 5px 0;
        }
        .comments {
            margin: 6px 0; 
            font-size: 14px;
            .comments-title {
                background-color: #ccc;
                font-size: 12px;
            }
        }
        .comments-body {
            padding: 0 10px;
        }
    }
</style>